package it.giuseppetrisciuoglio.lyrics.wordpress;

import it.giuseppetrisciuoglio.lyrics.persistence.entity.Artista;
import it.giuseppetrisciuoglio.lyrics.persistence.entity.Canzone;
import it.giuseppetrisciuoglio.lyrics.persistence.entity.MetaDataInfoCanzone;
import it.giuseppetrisciuoglio.lyrics.persistence.repository.ArtistaRepository;
import it.giuseppetrisciuoglio.lyrics.persistence.repository.CanzoneRepository;
import it.giuseppetrisciuoglio.lyrics.persistence.repository.MetaDataInfoCanzoneRepository;
import it.giuseppetrisciuoglio.lyrics.utils.StringUtilies;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ExportToWordpress {
	
	@Value("${wordpress.website}")
	private String website;
	
	@Value("${wordpress.title}")
	private String title;
	
	@Value("${wordpress.description}")
	private String description;
	
	@Value("${wordpress.author}")
	private String author;
	
	@Autowired
	private ArtistaRepository artistaRepository;
	
	@Autowired
	private CanzoneRepository canzoneRepository;
	
	@Autowired
	private MetaDataInfoCanzoneRepository metaDataInfoCanzoneRepository;
	
	private String cleanHTML(String html){
		html = StringUtilies.replaceBrWithNewLine(html);
		html = StringUtilies.stripHTMLtags(html);
		return StringUtilies.removeLyricsCredits(html);
	}
	
	private Document createDocument(){
		return DocumentFactory.getInstance().createDocument();
	}
	
	private String cleanHTML(String html){
		html = html.replaceAll("<br/>", "\n");
		return html.replaceAll("\\<.*?>","");
	}
	
	private Element createRootElement(Document doc){
		Element root = doc.addElement("rss");
		root.addAttribute("version", "2.0");
		root.addNamespace("excerpt", "http://wordpress.org/export/1.1/excerpt/");
		root.addNamespace("content", "http://purl.org/rss/1.0/modules/content/");
		root.addNamespace("wfw", "http://wellformedweb.org/CommentAPI/");
		root.addNamespace("dc", "http://purl.org/dc/elements/1.1/");
		root.addNamespace("wp", "http://wordpress.org/export/1.0/");
		root.addNamespace("xhtml", "http://www.w3.org/1999/xhtml");
		return root;
	}
	
	private Element createChannel(Element root){
		Element channel = root.addElement("channel");
		channel.addElement("title").addText(title);
		channel.addElement("link").addText(website);
		channel.addElement("description").addText(description);
		channel.addElement("pubDate").addText(toString(new Date()));
		channel.addElement("generator").addText("http://wordpress.org/?v=3.2.1");
		channel.addElement("language").addText("it");
		channel.addElement("wp:wxr_version").addText("1.1");
		channel.addElement("wp:base_site_url").addText(website);
		channel.addElement("wp:base_blog_url").addText(website);
		return channel;
	}
	
	private String toString(Date date, String pattern){
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		return simpleDateFormat.format(date);
	}
	
	private String toString(Date date){
		return toString(date, "ddd, dd MMM yyyy hh:mm:ss +0000");
	}
	
	private Element createCategoria(Element channel, Artista artista){
		Element category = channel.addElement("wp:category");
		category.addElement("wp:category_nicename").addText(artista.getNicename());
		category.addElement("wp:category_parent").addText("");
		Element catName = category.addElement("wp:cat_name");
		catName.addCDATA(artista.getNome());
		return category;
	}
	
	private void createCategorie(Element channel, List<Artista> artistas){
		for (Artista artista : artistas) {
			createCategoria(channel, artista);
		}
	}
	
	private void createTesto(Element channel, Canzone canzone, Artista artista){
		Element item = channel.addElement("item");
		item.addElement("title").addText(canzone.getTitolo());
		item.addElement("link").addText("");
		item.addElement("pubDate").addText(toString(new Date()));
		
		Element creator = item.addElement("dc:creator");
		creator.addCDATA(author);
		
		Element category = item.addElement("category");
		category.addAttribute("domain", "category");
		category.addAttribute("nicename", artista.getNicename());
		category.addCDATA(artista.getNome());

		Element guid = item.addElement("guid");
		guid.addAttribute("isPermalink", "false");
		guid.addText("");
		item.addElement("description").addText("");
		item.addElement("content:encoded").addCDATA(cleanHTML(canzone.getTesto()));
		item.addElement("excerpt:encoded").addCDATA("");
		item.addElement("wp:post_id").addText(canzone.getId().toString());
		item.addElement("wp:post_date").addText(toString(new Date()));
		item.addElement("wp:post_date_gmt").addText(toString(new Date()));
		item.addElement("wp:comment_status").addText("closed");
		item.addElement("wp:ping_status").addText("closed");
		item.addElement("wp:post_name").addText(canzone.getTitolo());
		item.addElement("wp:status").addText("publish");
		item.addElement("wp:post_parent").addText("0");
		item.addElement("wp:menu_order").addText("0");
		item.addElement("wp:post_type").addText("post");
		item.addElement("wp:post_password").addText("");
		item.addElement("wp:is_sticky").addText("0");
		
		// meta tags
		Element tags = item.addElement("wp:postmeta");
		tags.addElement("wp:meta_key").addText("title");
		tags.addElement("wp:meta_value").addText(canzone.getTitolo()+" Testo di "+artista.getNome());


		Element tags1 = item.addElement("wp:postmeta");
		tags1.addElement("wp:meta_key").addText("description");
		tags1.addElement("wp:meta_value").addText("Testo "+canzone.getTitolo()+" di "+artista.getNome()+", guarda il video, ascolta la canzone e leggi il testo originale del brano");
		
		createMetaDataTesto(item, canzone);

//		Element tags2 = item.addElement("wp:postmeta");
//		tags2.addElement("wp:meta_key").addText("_thumbnail_id");
//		tags2.addElement("wp:meta_value").addText("");
		
	}
	
	private void createMetaDataTesto(Element item, Canzone canzone){
		List<MetaDataInfoCanzone> datas = metaDataInfoCanzoneRepository.findByCanzone(canzone);
		for (MetaDataInfoCanzone metaDataInfoCanzone : datas) {
			createMetaDataTesto(item, "_gt_lyrics_".concat(metaDataInfoCanzone.getTipo()), metaDataInfoCanzone.getValore());
		}
	}
	
	
	private void createMetaDataTesto(Element item, String metaKey, String metaValue){
		Element tags = item.addElement("wp:postmeta");
		tags.addElement("wp:meta_key").addText(metaKey);
		tags.addElement("wp:meta_value").addText(metaValue);
	}
	
	private Document createXML() {
		Document doc = createDocument();
		Element root = createRootElement(doc);
		Element channel = createChannel(root);
		
		List<Artista> artistas = new ArrayList<Artista>(); 
		artistas.add(artistaRepository.findOne(1L));
		
		createCategorie(channel, artistas);
		
		for (Artista artista : artistas) {
			List<Canzone> canzones = canzoneRepository.findByArtistaAndTestoIsNotNull(artista);
			for (Canzone canzone : canzones) {
				createTesto(channel, canzone, artista);
			}
		}
		
		return doc;
	}
	
	public void exportXML() {
		try {
			File file = new File("c://Users//Dario//Desktop//ExportWorpress.xml");
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(file);
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(fos, format);
			writer.write(createXML());
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void insertAttachment(Element channel, ResultSet rs) throws SQLException {
		Element item = channel.addElement("item");
		item.addElement("title").addText("immagine: " + rs.getString("titolo"));
		item.addElement("link").addText("");
		SimpleDateFormat sdf = new SimpleDateFormat("ddd, dd MMM yyyy hh:mm:ss +0000");
		item.addElement("pubDate").addText(sdf.format(rs.getDate("data")));
		Element creator = item.addElement("dc:creator");
		creator.addCDATA(rs.getString("autore"));

		Element guid = item.addElement("guid");
		guid.addAttribute("isPermalink", "false");
		guid.addText("");
		item.addElement("description").addText(rs.getString("didascalia"));
		item.addElement("content:encoded").addCDATA("");
		item.addElement("excerpt:encoded").addCDATA("");
		item.addElement("wp:post_id").addText(rs.getBigDecimal("id_news").multiply(new BigDecimal(1000)).toString());
		sdf.applyPattern("yyyy-MM-dd hh:mm:ss");
		item.addElement("wp:post_date").addText(sdf.format(rs.getDate("data")));
		item.addElement("wp:post_date_gmt").addText("");
		item.addElement("wp:comment_status").addText("closed");
		item.addElement("wp:ping_status").addText("closed");
		item.addElement("wp:post_name").addText("Immagine: " + rs.getString("img_p"));
		item.addElement("wp:status").addText("inherit");
		item.addElement("wp:post_parent").addText(rs.getBigDecimal("id_news").toString());
		item.addElement("wp:menu_order").addText("0");
		item.addElement("wp:post_type").addText("attachment");
		item.addElement("wp:post_password").addText("");
		item.addElement("wp:is_sticky").addText("0");
		item.addElement("wp:attachment_url").addText("http://www.viaggiatorilowcost.it/immagini/news/" + rs.getString("img_p"));
	}

}
